﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace HaoPeng
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 根节点集合
        /// </summary>
        DataTable dt;
        /// <summary>
        /// 子节点集合
        /// </summary>
        DataTable dt1;
        /// <summary>
        /// 所有设备类型集合
        /// </summary>
        public string[] attributeArray = null;
        /// <summary>
        /// 当前设备类型的设备数量
        /// </summary>
        public int machineCount = -1;
        /// <summary>
        /// 程序主入口
        /// </summary>
        public Form1()
        {
            InitializeComponent();
            InitDataTable();
            InitDataTable1();
            BindRoot();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //展开所有树节点
            treeView1.ExpandAll();
            //创建定时器
            Timer timer1 = new Timer();
            timer1.Interval = 5000;
            timer1.Enabled = true;
            timer1.Tick += new EventHandler(timer1EventProcessor);//添加事件
        }
        /// <summary>
        /// 查询根节点集合
        /// </summary>
        private void InitDataTable()
        {
            try
            {
                string sql = "select * from tree_Floor";
                dt = SqlHelper.ExecuteDataset(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, sql).Tables[0];
            }
            catch (SqlException ex)
            {
                LogHelper.WriteLog("查询根节点错误：" + ex.Message);
            }
        }
        /// <summary>
        /// 查询子节点集合
        /// </summary>
        private void InitDataTable1()
        {
            try
            {
                string sql = "select * from tree_Machine";
                dt1 = SqlHelper.ExecuteDataset(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, sql).Tables[0];
            }
            catch (SqlException ex)
            {
                LogHelper.WriteLog("查询子节点错误：" + ex.Message);
            }
        }
        /// <summary>
        /// 绑定树
        /// </summary>
        private void BindRoot()
        {
            try
            {
                DataRow[] rows = dt.Select();//取根            
                foreach (DataRow dRow in rows)
                {
                    treeView1.ImageList = imageList1;
                    TreeNode rootNode = new TreeNode("", 0, 0);
                    rootNode.Tag = dRow;
                    rootNode.Text = dRow["FloorName"].ToString();
                    treeView1.Nodes.Add(rootNode);
                    //treeView1.Nodes[0].ImageIndex = 0;
                    BindChildAreas(rootNode);//调用添加子节点的方法
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("绑定树出现错误：" + ex.Message);
            }
        }
        /// <summary>
        /// 循环插入子节点到父节点
        /// </summary>
        /// <param name="fNode">父节点</param>
        private void BindChildAreas(TreeNode fNode)
        {
            try
            {
                DataRow dr = (DataRow)fNode.Tag;//父节点数据关联的数据行
                int fAreaId = (int)dr["ID"];    //父节点ID
                DataRow[] rows1 = dt1.Select("FloorID =" + fAreaId);//子区域            
                if (rows1.Length == 0)  //递归终止，区域不包含子区域时            
                {
                    return;
                }
                string flo = string.Empty;
                switch (dr["FloorName"].ToString())
                {
                    case "一楼设备": flo = "1"; break;
                    case "二楼设备": flo = "2"; break;
                    case "三楼设备": flo = "3"; break;
                    case "四楼设备": flo = "4"; break;
                    case "五楼设备": flo = "5"; break;
                    case "六楼设备": flo = "6"; break;
                    case "七楼设备": flo = "7"; break;
                    case "八楼设备": flo = "8"; break;
                    case "九楼设备": flo = "9"; break;
                    case "十楼设备": flo = "10"; break;
                    case "十一楼设备": flo = "11"; break;
                    case "十二楼设备": flo = "12"; break;
                }
                #region 读取所有设备类型并写入数组集合
                List<string> attribute_list = new List<string>();
                DataSet ddss = SqlHelper.ExecuteDataset(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, "select * from Attribute");
                int attribute_count = Convert.ToInt32(SqlHelper.ExecuteScalar(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, "select count(*) from Attribute"));
                for (int m = 0; m < attribute_count; m++)
                {
                    attribute_list.Add(ddss.Tables[0].Rows[m]["MachineType"].ToString());
                }
                attributeArray = attribute_list.ToArray();
                #endregion
                foreach (DataRow dRow in rows1)
                {
                    //tab标签的显示文本
                    string title = string.Empty;
                    TreeNode node = new TreeNode("", 2, 2);
                    node.Tag = dRow;
                    node.Text = dRow["MachineName"].ToString();
                    //添加子节点               
                    fNode.Nodes.Add(node);

                    //判断是否根节点，true则不生成新tab
                    if (node.Level == 0)
                    {
                        return;
                    }

                    title = dRow["MachineName"].ToString();
                    tabControl1.TabPages.Add(title + "(" + flo + ")", title + "(" + flo + ")");
                    tabControl1.SelectTab(title + "(" + flo + ")");

                    //绘制界面及数据
                    string sqlAttribute = "select * from Attribute where MachineType='" + title + "'";
                    string sqlMachine = "select * from Machine where MachineType='" + title + "'; select count(*) from Machine where MachineType='" + title + "'";
                    DataTable ddt = SqlHelper.ExecuteDataset(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, sqlAttribute).Tables[0];
                    DataSet dds = SqlHelper.ExecuteDataset(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, sqlMachine);
                    DataTable ddt1 = dds.Tables[0];
                    DataTable ddt2 = dds.Tables[1];
                    //取该设备类型所有参数
                    try
                    {
                        string[] AttributeName = ddt.Rows[0]["AttributeName"].ToString().Split(',');
                        //设备类型的参数展示
                        for (int i = 0; i < AttributeName.Length; i++)
                        {
                            Label lb = new Label();
                            lb.AutoSize = true;
                            lb.Location = new Point(30 + 75 * (i + 1), 50);
                            lb.Name = "label" + (i + 1);
                            lb.Size = new Size();
                            lb.TabIndex = 100;
                            lb.Text = AttributeName[i];
                            tabControl1.TabPages[title + "(" + flo + ")"].Controls.Add(lb);
                        }

                        int AttributeCount = Convert.ToInt32(ddt2.Rows[0][0]);
                        //每台设备的名称展示
                        for (int i = 0; i < AttributeCount; i++)
                        {
                            Label lb = new Label();
                            lb.AutoSize = true;
                            lb.Location = new Point(10, 50 + (14 * (i + 1)));
                            lb.Name = ddt1.Rows[i]["MachineName"].ToString();
                            lb.Size = new Size();
                            lb.TabIndex = 100;
                            lb.Text = ddt1.Rows[i]["MachineName"].ToString();
                            tabControl1.TabPages[title + "(" + flo + ")"].Controls.Add(lb);
                            //每台设备的嘟咔标签展示
                            for (int j = 0; j < AttributeName.Length; j++)
                            {
                                DookaControls.VariableInformation variableInformation = new DookaControls.VariableInformation();
                                DookaControls.Text_Label lb1 = new DookaControls.Text_Label();
                                lb1.AutoSize = true;
                                lb1.Location = new Point(30 + 75 * (j + 1), 50 + (14 * (i + 1)));
                                lb1.Name = ddt.Rows[0]["MachineEnglishName"].ToString() + (j + 1);
                                lb1.Size = new Size();
                                lb1.TabIndex = 100;
                                lb1.Text = "---";// ddt.Rows[0]["MachineEnglishName"].ToString() + (j + 1);
                                variableInformation.ID = ((uint)(1393u));
                                variableInformation.ValueIndex = ((uint)(0u));
                                variableInformation.SetName(ddt1.Rows[i]["MachineEnglishName"] + @"\" + ddt1.Rows[i]["Text" + (j + 1)]);
                                lb1.Variable = variableInformation;
                                tabControl1.TabPages[title + "(" + flo + ")"].Controls.Add(lb1);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        LogHelper.WriteLog("取设备类型参数过程出现错误：" + ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("取参数绘制界面过程报错：" + ex.Message);
            }
        }
        /// <summary>
        /// 定时器执行事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1EventProcessor(object sender, EventArgs e)
        {
            try
            {
                //所有设备类型循环
                for (int m = 0; m < attributeArray.Length; m++)
                {
                    string originalData = string.Empty;
                    //设备类型下的设备数量
                    machineCount = Convert.ToInt32(SqlHelper.ExecuteDataset(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, "select count(*) from Machine where MachineType='" + attributeArray[m] + "'").Tables[0].Rows[0][0].ToString());
                    //设备类型的设备表及设备参数表
                    DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, "select * from Machine where MachineType='" + attributeArray[m] + "';select * from Attribute where MachineType='" + attributeArray[m] + "'");
                    //设备类型的所有参数
                    string[] AttributeName = ds.Tables[1].Rows[0]["AttributeName"].ToString().Split(',');
                    //设备类型下的每台设备循环
                    for (int i = 0; i < machineCount; i++)
                    {
                        //清空取得的数据
                        originalData = string.Empty;
                        //循环每台设备的每个参数的PLC取得的值
                        for (int j = 0; j < Convert.ToInt32(AttributeName.Length); j++)
                        {
                            originalData += DookaControls.IO_Servers.GetVariableValue(ds.Tables[0].Rows[i]["MachineEnglishName"] + @"\" + ds.Tables[0].Rows[i]["Text" + (j + 1)]);
                            if (j < Convert.ToInt32(AttributeName.Length - 1))
                            {
                                originalData += "|";
                            }
                        }
                        //写入数据库
                        if (!string.IsNullOrEmpty(originalData) && originalData.Length > AttributeName.Length - 1)
                        {
                            string sqlStr = "insert into " + ds.Tables[1].Rows[0]["MachineEnglishName"] + "(DeviceName,Data,Datetime) values('" + ds.Tables[0].Rows[i]["MachineName"].ToString() + "','" + originalData + "',GETDATE())";
                            SqlHelper.ExecuteDataset(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, sqlStr);
                        }
                        #region 测试数据
                        //originalData = DookaControls.IO_Servers.GetVariableValue(@"HP2FzjJiaoBanJi1\VW166") + "|" +
                        //               DookaControls.IO_Servers.GetVariableValue(@"HP2FzjJiaoBanJi1\VW206") + "|" +
                        //               DookaControls.IO_Servers.GetVariableValue(@"HP2FzjJiaoBanJi1\VW148") + "|" +
                        //               DookaControls.IO_Servers.GetVariableValue(@"HP2FzjJiaoBanJi1\VW188") + "|" +
                        //               DookaControls.IO_Servers.GetVariableValue(@"HP2FzjJiaoBanJi1\VW500") + "|" +
                        //               DookaControls.IO_Servers.GetVariableValue(@"HP2FzjJiaoBanJi1\VW504") + "|" +
                        //               DookaControls.IO_Servers.GetVariableValue(@"HP2FzjJiaoBanJi1\VW100") + "|" +
                        //               DookaControls.IO_Servers.GetVariableValue(@"HP2FzjJiaoBanJi1\VW118");
                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("定时器写数据库数据过程出错：" + ex.Message);
            }
        }

        /// <summary>
        /// 树节点展开事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterExpand(object sender, TreeViewEventArgs e)
        {
            e.Node.ImageIndex = 1;        //指向展开的图标
            e.Node.SelectedImageIndex = 1;//指向展开选中的图标
        }
        /// <summary>
        /// 树节点收缩事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_AfterCollapse(object sender, TreeViewEventArgs e)
        {
            e.Node.ImageIndex = 0;        //指向关闭的图标
            e.Node.SelectedImageIndex = 0;//指向关闭选中的图标
        }
        /// <summary>
        /// 树节点（设备类型）点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            try
            {
                string flo = string.Empty;
                switch (e.Node.Parent.Text)
                {
                    case "一楼设备": flo = "1"; break;
                    case "二楼设备": flo = "2"; break;
                    case "三楼设备": flo = "3"; break;
                    case "四楼设备": flo = "4"; break;
                    case "五楼设备": flo = "5"; break;
                    case "六楼设备": flo = "6"; break;
                    case "七楼设备": flo = "7"; break;
                    case "八楼设备": flo = "8"; break;
                    case "九楼设备": flo = "9"; break;
                    case "十楼设备": flo = "10"; break;
                    case "十一楼设备": flo = "11"; break;
                    case "十二楼设备": flo = "12"; break;
                }
                //如果已经存在该节点的标签则选中标签
                if (tabControl1.TabPages.ContainsKey(e.Node.Text + "(" + flo + ")"))
                {
                    tabControl1.SelectTab(e.Node.Text + "(" + flo + ")");
                }
                #region 原树节点点击事件
                ////判断是否根节点，true则不生成新tab
                //if (e.Node.Level == 0)
                //{
                //    return;
                //}
                ////tab标签的显示文本
                //string title = e.Node.Text;
                ////判断是否已打开选中的节点标签
                //if (tabControl1.TabPages.ContainsKey(title))
                //{
                //    tabControl1.SelectTab(title);
                //}
                //else
                //{
                //    tabControl1.TabPages.Add(title, title);
                //    tabControl1.SelectTab(title);
                //    //绘制界面及数据
                //    string sqlAttribute = "select * from Attribute where MachineType='" + title + "'";
                //    string sqlMachine = "select * from Machine where MachineType='" + title + "'; select count(*) from Machine where MachineType='" + title + "'";
                //    DataTable ddt = SqlHelper.ExecuteDataset(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, sqlAttribute).Tables[0]
                //    DataSet dds = SqlHelper.ExecuteDataset(SqlHelper.ConnectionStringLocalTransaction, CommandType.Text, sqlMachine);
                //    DataTable ddt1 = dds.Tables[0];
                //    DataTable ddt2 = dds.Tables[1];
                //    //取该设备类型所以参数
                //    try
                //    {
                //        string[] AttributeName = ddt.Rows[0]["AttributeName"].ToString().Split(',');
                //        for (int i = 0; i < AttributeName.Length; i++)
                //        {
                //            Label lb = new Label();
                //            lb.AutoSize = true;
                //            lb.Location = new Point(30 + 75 * (i + 1), 50);
                //            lb.Name = "label" + (i + 1);
                //            lb.Size = new Size();
                //            lb.TabIndex = 100;
                //            lb.Text = AttributeName[i];
                //            tabControl1.TabPages[title].Controls.Add(lb);
                //        }

                //        int AttributeCount = Convert.ToInt32(ddt2.Rows[0][0]);
                //        for (int i = 0; i < AttributeCount; i++)
                //        {
                //            Label lb = new Label();
                //            lb.AutoSize = true;
                //            lb.Location = new Point(10, 50 + (14 * (i + 1)));
                //            lb.Name = ddt1.Rows[i]["MachineName"].ToString();
                //            lb.Size = new Size();
                //            lb.TabIndex = 100;
                //            lb.Text = ddt1.Rows[i]["MachineName"].ToString();
                //            tabControl1.TabPages[title].Controls.Add(lb);
                //            for (int j = 0; j < AttributeName.Length; j++)
                //            {
                //                DookaControls.VariableInformation variableInformation = new DookaControls.VariableInformation();
                //                DookaControls.Text_Label lb1 = new DookaControls.Text_Label();
                //                //Label lb1 = new Label();
                //                lb1.AutoSize = true;
                //                lb1.Location = new Point(30 + 75 * (j + 1), 50 + (14 * (i + 1)));
                //                lb1.Name = "zjjbj" + (j + 1);
                //                lb1.Size = new Size();
                //                lb1.TabIndex = 100;
                //                lb1.Text = "zjjbj" + (j + 1);
                //                variableInformation.ID = ((uint)(1393u));
                //                variableInformation.ValueIndex = ((uint)(0u));
                //                variableInformation.SetName(ddt1.Rows[i]["MachineEnglishName"] + @"\" + ddt1.Rows[i]["Text" + (j + 1)]);
                //                lb1.Variable = variableInformation;
                //                tabControl1.TabPages[title].Controls.Add(lb1);
                //            }
                //        }
                //    }
                //    catch (Exception ex)
                //    {
                //        MessageBox.Show("该设备没有设置参数，请查证！");
                //    }
                //}
                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("树节点点击事件报错：" + ex.Message);
            }
        }
        /// <summary>
        /// tab双击关闭事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tabControl1_DoubleClick(object sender, EventArgs e)
        {
            //tabControl1.TabPages.RemoveAt(tabControl1.SelectedIndex);
        }
        /// <summary>
        /// 添加标题栏
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void iOServers设置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //打开IO_Servers
                DookaControls.IoConfigurationClass.DevicesEditDlg();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("打开窗口失败：" + ex.Message);
            }            
        }

        private void 系统配置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DBset db = new DBset();
                db.ShowDialog();
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("打开窗口失败：" + ex.Message);
            }            
        }
    }
}
